package com.lucenly.card.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.TrafficStats;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.text.format.Formatter;

import com.siberiadante.toastutils.ToastUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.List;

import static android.content.Context.CLIPBOARD_SERVICE;

/**
 * author: Admin
 * time  : 6/16 0016
 * desc  :
 */

public class PhoneInfo {

    private static PhoneInfo instance;
    private TelephonyManager tm;
    private Activity act;
    private final static String XCHANNEL = "X_CHANNEL";

    private PhoneInfo(Activity act) {
        tm = (TelephonyManager) act.getSystemService(Context.TELEPHONY_SERVICE);
        this.act = act;
    }

    public static PhoneInfo getInstance(Activity act) {
        if (instance == null) {
            instance = new PhoneInfo(act);
        } else if (instance.act != act) {
            instance = new PhoneInfo(act);
        }
        return instance;
    }

    /**
     * 获取手机号码
     */
    @SuppressLint("MissingPermission")
    public String getPhoneNumber() {
        return tm == null ? "" : tm.getLine1Number();
    }
    /**
     * 获得应用包名
     */
    public String getAppProcessName() {
        //当前应用pid
        int pid = android.os.Process.myPid();
        //任务管理类
        ActivityManager manager = (ActivityManager) act.getSystemService(Context.ACTIVITY_SERVICE);
        //遍历所有应用
        List<ActivityManager.RunningAppProcessInfo> infos = manager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo info : infos) {
            if (info.pid == pid)//得到当前应用
                return info.processName;//返回包名
        }
        return "";
    }
    /**
     * 获得软件版本号
     */
    public int getVerCode() {
        int verCode = -1;
        try {
            verCode = act.getPackageManager().getPackageInfo(act.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verCode;
    }

    public String getVersionName() {
        String versionName = "";
        try {
            versionName = act.getPackageManager().getPackageInfo(act.getPackageName(), PackageManager.GET_ACTIVITIES).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

    public String getVerName() {
        return getVersionName().split("_")[1];
    }

    /**
     * 获得APP名称
     */
    public String getAppName() {
        String appName = "";
        try {
            PackageManager packageManager = act.getPackageManager();
            ApplicationInfo applicationInfo = packageManager.getApplicationInfo(act.getPackageName(), 0);
            appName = (String) packageManager.getApplicationLabel(applicationInfo);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return appName;
    }

    /**
     * 获取渠道名(标号)
     */
    public String getChannelName() {
        String channelName = "";
        try {
            PackageManager packageManager = act.getPackageManager();
            if (packageManager != null) {
                //注意此处为ApplicationInfo 而不是 ActivityInfo,因为友盟设置的meta-data是在application标签中，而不是某activity标签中，所以用ApplicationInfo
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(act.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        channelName = applicationInfo.metaData.getInt("UMENG_CHANNEL") + "";
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return channelName;
    }

    public String getChannelKey() {
        String key = "";
        try {
            ApplicationInfo appInfo = act.getPackageManager()
                    .getApplicationInfo(act.getPackageName(), PackageManager.GET_META_DATA);
            if (appInfo != null) {
                if (appInfo.metaData != null) {
                    key = appInfo.metaData.getString(XCHANNEL).split("_@_")[0];
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
        }
        return key;
    }

    public String getChannelValue() {
        String valu = "";
        try {
            ApplicationInfo appInfo = act.getPackageManager()
                    .getApplicationInfo(act.getPackageName(), PackageManager.GET_META_DATA);
            if (appInfo != null) {
                if (appInfo.metaData != null) {
                    valu = appInfo.metaData.getString(XCHANNEL).split("_@_")[1];
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
        }
        return valu;
    }

    /**
     * 获取手机IMEI
     */
    public String getIMEI() {
        return tm == null ? "" : tm.getDeviceId();
    }

    /**
     * 获取手机AndroidId
     */
    public String getAndroidId() {
        return Settings.Secure.getString(act.getContentResolver(), Settings.Secure.ANDROID_ID);
    }

    /**
     * 获取手机品牌
     */
    public String getBrand() {
        return Build.BRAND;
    }

    /**
     * 获取手机型号
     *
     * @return
     */
    public String getPhoneModel() {
        return Build.MODEL;
    }

    /**
     * 获取手机屏幕宽
     */
    public int getScreenWidth() {
        return act.getWindowManager().getDefaultDisplay().getWidth();
    }

    /**
     * 获取手机屏高宽
     */
    public int getScreenHeight() {
        return act.getWindowManager().getDefaultDisplay().getHeight();
    }

    /**
     * 获取手机系统版本
     */
    public String getAndVersion() {
        return Build.VERSION.RELEASE;
    }

    /**
     * 获取手机可用内存
     */
    public String getAvailMemory() {// 获取android当前可用内存大小
        ActivityManager am = (ActivityManager) act.getSystemService(Context.ACTIVITY_SERVICE);
        MemoryInfo mi = new MemoryInfo();
        am.getMemoryInfo(mi);
        //mi.availMem; 当前系统的可用内存
        return Formatter.formatFileSize(act.getBaseContext(), mi.availMem);// 将获取的内存大小规格化
    }

    /**
     * 获取运营商
     */
    public String getProvidersName() {
        String ProvidersName = "";
        // 返回唯一的用户ID;就是这张卡的编号神马的
        String IMSI = tm.getSubscriberId();
        // IMSI号前面3位460是国家，紧接着后面2位00 02是中国移动，01是中国联通，03是中国电信。
        if (IMSI != null && !IMSI.equals("")) {
            if (IMSI.startsWith("46000") || IMSI.startsWith("46002")) {
                ProvidersName = "中国移动";
            } else if (IMSI.startsWith("46001")) {
                ProvidersName = "中国联通";
            } else if (IMSI.startsWith("46003")) {
                ProvidersName = "中国电信";
            }
        }
        return ProvidersName;
    }

    /**
     * 获取手机内存
     */
    public String getTotalMemory() {
        try {
            FileInputStream fis = new FileInputStream(new File("/proc/meminfo"));
            //包装一个一行行读取的流
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis));
            //取到所有的内存信息
            String memTotal = bufferedReader.readLine();

            StringBuffer sb = new StringBuffer();

            for (char c : memTotal.toCharArray()) {

                if (c >= '0' && c <= '9') {
                    sb.append(c);
                }
            }
            //为了方便格式化 所以乘以1024
            long totalMemory = Long.parseLong(sb.toString()) * 1024;

            return Formatter.formatFileSize(act, totalMemory);

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 获取手机的流量值
     */
    public long getTotalRxValue(final int state) {
        long flow = 0;
        // 得到整个手机的流量值
        if (state == 1) {
            flow = TrafficStats.getUidRxBytes(act.getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ? 0
                    : (TrafficStats.getTotalRxBytes() /*/ 1024*/);// 转为KB
        } else if (state == 2) {
            // 得到当前应用的流量值
            flow = TrafficStats.getUidRxBytes(act.getApplicationInfo().uid) ==
                    TrafficStats.UNSUPPORTED ? 0 : (TrafficStats
                    .getUidRxBytes(act.getApplicationInfo().uid)/* / 1024*/);// 转为KB
        }
        return flow;
    }

    /**
     * 获取手机连接的网络类型（是WIFI还是手机网络[2G/3G/4G]）
     */

    public String getNetWorkStatus() {
        String netWorkType = "";
        ConnectivityManager connectivityManager = (ConnectivityManager) act
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isConnected()) {
            int type = networkInfo.getType();
            if (type == ConnectivityManager.TYPE_WIFI) {
                netWorkType = "Wifi";
            } else if (type == ConnectivityManager.TYPE_MOBILE) {
                if (getNetWorkClass() == 1) {
                    netWorkType = "Wifi";
                } else if (getNetWorkClass() == 2) {
                    netWorkType = "2G";
                } else if (getNetWorkClass() == 3) {
                    netWorkType = "3G";
                } else if (getNetWorkClass() == 4) {
                    netWorkType = "4G";
                }
            }
        }
        return netWorkType;
    }

    /**
     * 获取手机网络类型（2G/3G/4G）
     */
    public int getNetWorkClass() {
        TelephonyManager telephonyManager = (TelephonyManager) act.getSystemService(Context.TELEPHONY_SERVICE);

        switch (telephonyManager.getNetworkType()) {
            case TelephonyManager.NETWORK_TYPE_GPRS:
            case TelephonyManager.NETWORK_TYPE_EDGE:
            case TelephonyManager.NETWORK_TYPE_CDMA:
            case TelephonyManager.NETWORK_TYPE_1xRTT:
            case TelephonyManager.NETWORK_TYPE_IDEN:
                return 2;
            case TelephonyManager.NETWORK_TYPE_UMTS:
            case TelephonyManager.NETWORK_TYPE_EVDO_0:
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
            case TelephonyManager.NETWORK_TYPE_HSDPA:
            case TelephonyManager.NETWORK_TYPE_HSUPA:
            case TelephonyManager.NETWORK_TYPE_HSPA:
            case TelephonyManager.NETWORK_TYPE_EVDO_B:
            case TelephonyManager.NETWORK_TYPE_EHRPD:
            case TelephonyManager.NETWORK_TYPE_HSPAP:
                return 3;
            case TelephonyManager.NETWORK_TYPE_LTE:
                return 4;
            default:
                return 0;
        }
    }

    /**
     * 用来获取手机拨号上网IP
     */
    public String getPsdnIp() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        //if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet6Address) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (Exception e) {
            return "";
        }
        return "";
    }

    public String secretCode(int nos) {
        String code;
        try {
            Calendar now = Calendar.getInstance();
            String str = getVersionName().split("_")[1].replaceAll("\\.", "");
            String num = str.substring(str.length() - 2, str.length()) + nos + (now.get(Calendar.DAY_OF_MONTH) - 1) + (now.get(Calendar.HOUR_OF_DAY) + 1);
            code = "*#" + Integer.toHexString(Integer.valueOf(num)) + "#*";
//            Log.e("str....>", num + "_" + code);
        } catch (Exception e) {
            return null;
        }
        return code;
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    public String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

    public boolean canDownloadState() {
        try {
            int state = act.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");

            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean isAppToBackground() {
        ActivityManager am = (ActivityManager) act.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(act.getPackageName())) {
//                Log.i("后台", "........");
                return true;
            }
        }
        return false;
    }

    public void setClip(String txt) {
        if (Build.VERSION.SDK_INT > 11) {
            android.content.ClipboardManager c = (android.content.ClipboardManager) act.getSystemService(CLIPBOARD_SERVICE);
            c.setPrimaryClip(ClipData.newPlainText("text", txt));
        } else {
            android.text.ClipboardManager c = (android.text.ClipboardManager) act.getSystemService(CLIPBOARD_SERVICE);
            c.setText(txt);
        }
    }

    public String getClip() {
        String con;
        if (Build.VERSION.SDK_INT > 11) {
            android.content.ClipboardManager c = (android.content.ClipboardManager) act.getSystemService(CLIPBOARD_SERVICE);
            con = c.getPrimaryClip().getItemAt(0).getText().toString();
        } else {
            android.text.ClipboardManager c = (android.text.ClipboardManager) act.getSystemService(CLIPBOARD_SERVICE);
            con = c.getText().toString();
        }
        return con;
    }

    public static Intent getAppDetailSettingIntent(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
        }
        return localIntent;
    }
}
